package com.codec;

import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;


public class MessageEncoder extends ProtocolEncoderAdapter {
	
	private final Charset charset;
	
	public MessageEncoder(Charset charset){
		this.charset = charset;
	}
	
	public void encode(IoSession session, Object message,ProtocolEncoderOutput out) throws Exception {
		CharsetEncoder ce = charset.newEncoder();				
		MessagePack msgPack = (MessagePack) message;         
        IoBuffer buf = IoBuffer.allocate(msgPack.getLength());  
        buf.setAutoExpand(true); 
        
        byte[] bytLen = new byte[4];
        ByteUtil.putInt(bytLen, msgPack.getLength(), 0);
        
        byte[] bytType = new byte[4];
        ByteUtil.putInt(bytType, msgPack.getType(), 0);
        
        byte[] bytRequestid = new byte[4];
        ByteUtil.putInt(bytRequestid, msgPack.getRequestid(), 0);
        
        buf.put(bytLen);     
        buf.put(bytType);   
        buf.put(bytRequestid);     
        if (msgPack.getContent() != null){      		
        	buf.put(msgPack.getContent().getBytes("utf-8"));   
        }       
        buf.flip();     
        out.write(buf);  
	}

}
